import React from 'react';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import useAuthStore from '../../stores/authStore';
import './index.less';

const Login = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { login, isAuthenticated } = useAuthStore();
  const [form] = Form.useForm();

  // 如果已经登录，跳转到回调路径或首页
  React.useEffect(() => {
    if (isAuthenticated) {
      const callback = searchParams.get('callback');
      navigate(callback || '/', { replace: true });
    }
  }, [isAuthenticated, navigate, searchParams]);

  const handleSubmit = async (values) => {
    try {
      const res = await login(values);
      if (res.code === 0) {
        message.success('登录成功');
        // 获取回调路径
        const callback = searchParams.get('callback');
        navigate(callback || '/', { replace: true });
      } else {
        message.error(res.msg || '登录失败');
      }
    } catch (error) {
      message.error('登录失败，请稍后重试');
    }
  };

  return (
    <div className="login-page">
      <div className="login-container">
        <div className="login-content">
          <div className="login-header">
            <h1>教师管理系统</h1>
            <p>欢迎回来，请登录您的账号</p>
          </div>
          <Form
            form={form}
            name="login"
            onFinish={handleSubmit}
            autoComplete="off"
            size="large"
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input 
                prefix={<UserOutlined />} 
                placeholder="请输入您的用户名" 
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
              extra="默认密码：123456"
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="请输入密码"
              />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};

export default Login; 